package com.mygame.components

import com.almasb.fxgl.dsl.FXGL
import com.almasb.fxgl.dsl.components.HealthIntComponent
import com.almasb.fxgl.entity.Entity
import com.almasb.fxgl.entity.SpawnData
import com.almasb.fxgl.entity.component.Component
import com.almasb.fxgl.entity.components.IDComponent
import com.almasb.fxgl.entity.getComponent
import com.almasb.fxgl.entity.state.StateComponent
import com.mygame.Const
import com.mygame.EType
import com.mygame.changePoint
import com.mygame.spawn
import javafx.scene.paint.Color
import javafx.util.Duration
import java.util.Random
import kotlin.jvm.optionals.getOrNull

class AttackComponent : Component() {
    private var lastAttackTime: Long = 0L
    private var tagEntity: Entity? = null
    private lateinit var stateComponent: StateComponent

    override fun onAdded() {
        stateComponent = entity.getComponent(StateComponent::class.java)
        tagEntity = entity.properties.getValueOptional<Entity>(Const.TAG_ENTITY).getOrNull()
    }

    override fun onUpdate(tpf: Double) {
        if (!entity.isActive) return
        tagEntity?.let {
            if (!it.isActive) return
            if (stateComponent.currentState != RUN && it.distanceBBox(entity) < 100) {//不是行走状态
                if (System.currentTimeMillis() - lastAttackTime < 1000) {//在一定的间隔时间
                    return
                }
                lastAttackTime = System.currentTimeMillis()
                stateComponent.changeState(ATTACK)//切换成攻击状态
                println("${stateComponent.currentState}  ${entity.properties.getString(Const.NAME)} 发起攻击")
                val r = 10.0
                val speed = 500.0
                val dir = it.center.subtract(entity.center).normalize()
                spawn(
                    EType.BULLET,
                    SpawnData(entity.center.x - r, entity.center.y - r)
                        .put(Const.RADIUS, r)
                        .put(Const.DIR, dir)
                        .put(Const.SPEED, speed)
                        .put(Const.COLOR, Color.BLACK)
                )
                FXGL.getGameTimer().runOnceAfter({
                    if (entity.isActive) {
                        stateComponent.changeState(IDLE)//切回闲置状态
                    }
                }, Duration.seconds(0.5))
                val hpEntity = it.properties.getObject<Entity>(Const.HP_ENTITY)
                val hpComponent = hpEntity.getComponent(HealthIntComponent::class.java)
                val point = -5 + Random().nextInt(15)
                hpComponent.changePoint(point)
                println("攻击${point},玩家${it.getComponent<IDComponent>().id} 剩下: ${hpComponent.value}")
                if (hpComponent.value <= 0) {
                    println("玩家死亡")
                }
            }
        }
    }

}